import { Button, Collapse, DatePicker, Empty, InputNumber, Menu, message, Modal, Tooltip } from 'antd'

import { favoritesquery, filtersList, getDataItemPolymerizeOptions, queryList, SelectDatesList } from '@/api/Database'

import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons'

import { HsAdminInput, HsAdminSpin } from '@hs-admin/base-components'

import { ServerCascader, ServerAreaSelect, ServerCheckboxList, ServerSelect } from '@hs-server/components'

import { HsAdminSelecPark } from '@/components/GlobalScrollSelect'

import { useSearchParams } from 'react-router-dom'

import { Resizable } from 'react-resizable'

import { useEffect, useState } from 'react'

import 'react-resizable/css/styles.css'

import classNames from 'classnames'

import { favorFilter } from '../utils/favorFilterData'

import dayjs from 'dayjs'

import './search.css'
import { getItem, removeItem, USERRESULT } from '@hs-admin/utils'

import { HonorTreeData } from '@/utils/SearchTreeData'

const Search = (props: any) => {
  const [searchParams] = useSearchParams()

  const { RangePicker } = DatePicker

  const { Inputsearch, success, CancelData } = props

  const userResult = getItem(USERRESULT)

  const [Databasekeywords, setDatabasekeywords] = useState('') // 数据库关键字搜索

  const [isModalOpen, setIsModalOpen] = useState(false)

  const [items, setItems]: any = useState([])

  const [Collapseitems, setCollapseitems] = useState([])

  const [loading, setloading] = useState(false)

  const [SelectItemid, setSelectItemid]: any = useState(null)

  const [ParkList, setParkList] = useState('false')

  const [state, setState] = useState({ width: 240 })

  const [filterState, setFilterState] = useState({ width: 300 })

  //获取当前时间戳并转成年月日时分秒格式
  const nowTime = dayjs().format('YYYY-MM-DD HH:mm:ss')

  const [favoritessearchValue, setfavoritessearchValue] = useState('')

  const [keywords, setkeywords] = useState('')

  const [favoritesList, setfavoritesList] = useState([])

  const [isqueryListModalOpen, setisqueryListModalOpen] = useState(false)

  const [startInputNumber, setStartInputNumber]: any = useState(null)

  const [endInputNumber, setendInputNumber]: any = useState(null)

  const [searchValue, setsearchValue]: any = useState({
    release_item_id: '',
    keywords: '',
    filters: {
      pca: [],
      polymerize: [],
      date: [],
      park: [],
      time: [],
      industry: [],
      national_economy_classification: [],
      strategic_industry: [],
      qualification: [],
      number_range: []
    },
    relation: null,
    ids: null
  })
  const [collapsed, setCollapsed] = useState(false)

  const onResize = (_event: any, { size }: any) => {
    setState({ width: size.width < 150 ? 150 : size.width })
    if (size.width >= 240) {
      setCollapsed(false)
    }
  }
  const onFilterResize = (_event: any, { size }: any) => {
    setFilterState({ width: size.width < 200 ? 200 : size.width })
  }
  const toggleCollapsed = () => {
    if (!collapsed) {
      setCollapsed(true)
      setState({ width: 46 })
    } else {
      setCollapsed(false)
      setState({ width: 240 })
    }
  }

  //点击左边数据库 获取数据筛选项
  const handleSelectItem = (e: any) => {
    setSelectItemid(e.key)

    setDatabasekeywords('')

    setsearchValue((prevItems: any) => {
      return {
        ...prevItems,
        release_item_id: e.key,
        relation: null
      }
    })

    cleanSearchvalue()

    CancelData(null) //清除数据
  }

  const handleOk = () => {
    favorites()
  }

  const handleCancel = () => {
    setIsModalOpen(false)
    setfavoritessearchValue('')
  }

  const getfiltersList = () => {
    setloading(true)
    // 获取筛选列表数据
    filtersList({ page: 1, page_size: 9999, id: SelectItemid })
      .then((res) => {
        setCollapseitems(res.items)
        if (res.items.findIndex((its: any) => its.type === 'park') !== -1) {
          setParkList('true')
        }
      })
      .finally(() => setloading(false))
  }

  const getMenuList = () => {
    SelectDatesList().then((res) => {
      res.map((item: any) => {
        item.key = item.id
        item.label = item.name
        item.children = item.items.map((its: any) => {
          its.key = its.id
          its.label = its.data_item_product.name
          return its
        })
      })
      setItems(res)
    })
  }

  useEffect(() => {
    if (!SelectItemid && items.length) {
      setSelectItemid(items[0].children[0].key)
      setsearchValue((prevItems: any) => {
        return { ...prevItems, release_item_id: items[0].children[0].key }
      })
    }
  }, [items])

  const ModalOpen = () => {
    setisqueryListModalOpen(true)
  }

  //获取收藏筛选项的列表
  const getqueryList = () => {
    queryList({
      keywords: keywords,
      release_item_id: SelectItemid,
      page: 1,
      page_size: 9999
    }).then((_res: any) => {
      setfavoritesList(_res.items)
    })
  }

  // 根据导入数据，将数据回显到下面的筛选框中
  const handleCleanData = (row: any) => {
    //关闭导入筛选框
    setisqueryListModalOpen(false)
    //清空导入筛选框的模糊查询输入框
    setkeywords('')

    favorFilter(row, setsearchValue, setDatabasekeywords)

    message.success('导入成功')
  }

  const Infofavoritesquery = () => {
    if (
      Inputsearch !== '' ||
      searchValue.filters.pca.length ||
      searchValue.filters.polymerize.length ||
      searchValue.filters.date.length ||
      searchValue.filters.park.length ||
      searchValue.filters.time.length ||
      searchValue.filters.industry.length ||
      searchValue.filters.national_economy_classification.length
    ) {
      setfavoritessearchValue(`${nowTime} ${userResult.name}筛选收藏`)
      setIsModalOpen(true)
    } else message.error('请选择收藏的筛选项')
  }

  //收藏筛选
  const favorites = () => {
    const items: any = []
    Object.keys(searchValue.filters).forEach((key) => items.push(...searchValue.filters[key]))
    const data: any = {
      release_item_id: SelectItemid,
      name: favoritessearchValue,
      filters: {
        keywords: Inputsearch,
        items
      }
    }
    favoritesquery(data).then((_res) => {
      handleCancel()
      message.success('收藏成功')
    })
  }

  //数据筛选组件选中的值
  const DataSelectsuccess = (e: any, item?: any) => {
    const obj: any = {
      name: item.name,
      type: item.type,
      config: {}
    }

    if (item.type === 'pca') {
      obj.config = {
        province_column: item.config.province_column,
        city_column: item.config.city_column,
        area_column: item.config.area_column,
        values: e
      }
    } else if (item.type === 'polymerize' || item.type === 'park' || item.type === 'qualification') {
      obj.config = {
        column: item.config.column
      }
      const logs: any = []

      //qualification 资质信息
      if (item.type === 'qualification') {
        e.map((its: any) => {
          logs.push({ show: its, value: its })
        })
      } else {
        e.map((its: any) => {
          logs.push({ show: its.label, value: its.value })
        })
      }

      obj.config.values = logs
    } else {
      obj.config = {
        // column: item.config.column, 先写死
        column: item.type === 'industry' ? 'hs_ind_list' : 'nea_ind_list',
        values: e
      }
    }

    setsearchValue((prevItems: any) => {
      const preValue = (prevItems.filters[item.type] ?? []).filter((it: any) => it.name !== obj.name)
      prevItems.filters[item.type] = obj.config.values.length ? [...preValue, obj] : [...preValue]
      return { ...prevItems }
    })
  }

  //处理options数据结构
  const Selectdata: any = (list: any, key: any, label: any) => {
    const arr: any = []
    list.map((item: any) => {
      const obj = {
        value: key ? item[key] : item,
        label: label ? item[label] : item
      }
      arr.push(obj)
    })
    return arr
  }

  // 时间筛选年月日
  const handleTimeRankonChange = (datesting: any, item: any, type: any) => {
    const obj: any = {
      name: item.name,
      type: item.type,
      config: {
        column: item.config.column,
        start: {
          show: datesting[0],
          value: datesting[0]
        },
        end: {
          show: datesting[1],
          value: datesting[1]
        }
      }
    }

    if (datesting[0]) {
      setsearchValue((prevItems: any) => {
        const preValue = (prevItems.filters[item.type] ?? []).filter((it: any) => it.name !== obj.name)
        prevItems.filters[type] = [obj, ...preValue]
        return { ...prevItems }
      })
    } else {
      setsearchValue((prevItems: any) => {
        const preValue = (prevItems.filters[item.type] ?? []).filter((it: any) => it.name !== obj.name)
        prevItems.filters[type] = preValue
        return { ...prevItems }
      })
    }
  }

  const polymerizeFocus = (item: { config: { column: any; options: any[] } }) => {
    if (!item.config.options.length) {
      setloading(true)
      getDataItemPolymerizeOptions({
        id: SelectItemid,
        column_name: item.config.column
      })
        .then((res) => {
          item.config.options = res
          setCollapseitems([...Collapseitems])
        })
        .finally(() => {
          setloading(false)
        })
    }
  }
  const filterOption = (item: any, value: any) => {
    /* 聚合 */
    if (value && item.type === 'polymerize') {
      return (
        <ServerSelect
          modelValue={searchValue.filters.polymerize.filter((it: any) => it.name === item.name) ?? []}
          options={Selectdata(value)}
          success={(e: any) => DataSelectsuccess(e, item)}
          onFocus={() => polymerizeFocus(item)}
        />
      )
    }

    /* 区域筛选 */
    if (item.type === 'pca') {
      return (
        <ServerAreaSelect
          modelValue={searchValue.filters.pca.filter((it: any) => it.name === item.name) ?? []}
          success={(e: any) => DataSelectsuccess(e, item)}
        />
      )
    }

    /* 园区筛选 */
    if (item.type === 'park') {
      return (
        <HsAdminSelecPark
          className="w-full"
          placeholder="请选择"
          mode="multiple"
          parklist={ParkList}
          value={searchValue.filters.park.filter((it: any) => it.name === item.name)?.[0]?.config?.values?.map((itt: any) => itt.value) ?? []}
          onChange={(_e: string, option: any) => {
            DataSelectsuccess(option, item)
          }}
        />
      )
    }

    /* 时间选择器 */
    if (item.type === 'date') {
      let value: any = null
      const theOne = searchValue.filters.date.find((it: any) => it.name === item.name)
      if (theOne) {
        let start = null
        let end = null
        if (theOne.config?.start?.value) {
          start = dayjs(theOne.config?.start?.value)
        }
        if (theOne.config?.end?.value) {
          end = dayjs(theOne.config?.end?.value)
        }
        value = [start, end]
      }
      return (
        <div>
          <div className="flex items-center">
            <RangePicker
              value={value}
              onChange={(_date, datestr) => handleTimeRankonChange(datestr, item, 'date')}
              placeholder={['开始日期', '结束日期']}
            />
          </div>
        </div>
      )
    }

    /** 时间选择器 时分秒 */
    if (item.type === 'time') {
      let value: any = null
      const theOne = searchValue.filters.time.find((it: any) => it.name === item.name)
      if (theOne) {
        let start = null
        let end = null
        if (theOne.config?.start?.value) {
          start = dayjs(theOne.config?.start?.value)
        }
        if (theOne.config?.end?.value) {
          end = dayjs(theOne.config?.end?.value)
        }
        value = [start, end]
      }
      return (
        <div>
          <RangePicker
            value={value}
            showTime
            onChange={(_date, datestr) => handleTimeRankonChange(datestr, item, 'time')}
            placeholder={['开始日期', '结束日期']}
          />
        </div>
      )
    }

    /* 产业筛选 */
    if (item.type === 'industry') {
      return (
        <ServerCascader
          modelValue={searchValue.filters.industry.filter((it: any) => it.name === item.name) ?? []}
          type={'industry'}
          success={(e: any) => DataSelectsuccess(e, item)}
        />
      )
    }

    /* 国民经济分类筛选 */
    if (item.type === 'national_economy_classification') {
      return (
        <div>
          <ServerCascader
            modelValue={searchValue.filters.national_economy_classification.filter((it: any) => it.name === item.name) ?? []}
            type={'national'}
            success={(e: any) => DataSelectsuccess(e, item)}
          />
        </div>
      )
    }

    /* 战略性新兴产业分类筛选 */
    if (item.type === 'strategic_industry') {
      return (
        <div>
          <ServerCascader
            modelValue={searchValue.filters.strategic_industry?.filter((it: any) => it.name === item.name) ?? []}
            type={'strategic_industry'}
            success={(e: any) => DataSelectsuccess(e, item)}
          />
        </div>
      )
    }

    /* 资质信息 */
    if (item.type === 'qualification') {
      const List: any = []
      searchValue.filters.qualification?.map((it: any) => {
        it.config.values.map((item: any) => {
          List.push(item.show)
        })
      })
      return (
        <div>
          <ServerCheckboxList
            treeData={HonorTreeData}
            modelValue={searchValue.filters.qualification?.filter((it: any) => it.name === item.name) ? List : []}
            success={(e: any) => {
              DataSelectsuccess(e, item)
            }}
          />
        </div>
      )
    }

    /* 最新市值(亿元) */
    if (item.type === 'number_range') {
      return (
        <div className="flex items-center">
          <InputNumber
            placeholder="请输入"
            changeOnBlur
            controls={false}
            type="number"
            value={startInputNumber}
            onChange={(value) => {
              setStartInputNumber(value)
            }}
            onBlur={() => number_onChange(item, 'number_range')}
          />
          ~
          <InputNumber
            placeholder="请输入"
            controls={false}
            type="number"
            value={endInputNumber}
            onChange={(value) => {
              setendInputNumber(value)
            }}
            onBlur={() => {
              number_onChange(item, 'number_range')
            }}
          />
        </div>
      )
    }
  }

  const number_onChange = (item: any, type: any) => {
    const newStart = startInputNumber
    let newEnd = endInputNumber
    if (newEnd && newStart > newEnd) {
      newEnd = null
      setendInputNumber(null)
    }

    const obj: any = {
      name: item.name,
      type: item.type,
      config: {
        column: item.config.column,
        start: newStart,
        end: newEnd
      }
    }
    if (newStart) {
      setsearchValue((prevItems: any) => {
        const preValue = (prevItems.filters[item.type] ?? []).filter((it: any) => it.name !== obj.name)
        prevItems.filters[type] = [obj, ...preValue]
        return { ...prevItems }
      })
    } else {
      setsearchValue((prevItems: any) => {
        const preValue = (prevItems.filters[item.type] ?? []).filter((it: any) => it.name !== obj.name)
        prevItems.filters[type] = preValue
        return { ...prevItems }
      })
    }
  }

  //清除所有筛选项
  const cleanSearchvalue = () => {
    setsearchValue((prevItems: any) => {
      return {
        ...prevItems,
        filters: {
          pca: [],
          polymerize: [],
          date: [],
          park: [],
          time: [],
          industry: [],
          national_economy_classification: [],
          strategic_industry: [],
          qualification: [],
          number_range: []
        }
      }
    })
    setendInputNumber(null)
    setStartInputNumber(null)
  }

  useEffect(() => {
    if (SelectItemid) success(searchValue, Databasekeywords)
  }, [searchValue, Databasekeywords])

  useEffect(() => {
    SelectItemid && getfiltersList()
  }, [SelectItemid])

  useEffect(() => {
    isqueryListModalOpen && getqueryList()
  }, [isqueryListModalOpen])

  useEffect(() => {
    getMenuList()
  }, [])

  useEffect(() => {
    //首页带回来回显 数据库id和搜索keywords
    if (searchParams.get('id') || searchParams.get('keywords')) {
      const keywords: any = searchParams.get('keywords')
      const id: any = searchParams.get('id')
      setDatabasekeywords(keywords)
      setSelectItemid(id)
      setsearchValue((prevItems: any) => {
        prevItems.release_item_id = id
        return { ...prevItems }
      })
    }
    //个人中心带回来导入筛选项的值
    if (searchParams.get('from')) {
      if (getItem('favorFilter')) {
        const getfavorFilter = getItem('favorFilter')

        removeItem('favorFilter')

        setSelectItemid(getfavorFilter.release_item.id)

        setsearchValue((prevItems: any) => {
          prevItems.release_item_id = getfavorFilter.release_item.id
          return { ...prevItems }
        })

        favorFilter(getfavorFilter, setsearchValue, setDatabasekeywords)
      }
    }
  }, [])

  return (
    <div className="flex h-100% pageSeach-box">
      <Resizable height={0} width={state.width} onResize={onResize}>
        <div style={{ width: state.width + 'px', borderRight: 0 }} className="overflow-auto boxstyle">
          <div className="flex h-4% datatype p-15px font-bold justify-between w-100%">
            <div className="">选择数据</div>
          </div>
          {!collapsed && (
            <Menu
              style={{ height: '90%' }}
              selectedKeys={[SelectItemid]}
              defaultOpenKeys={[items[0]?.key]}
              onSelect={handleSelectItem}
              mode="inline"
              inlineCollapsed={false}
              items={items}
            />
          )}
          <Button type="primary" onClick={toggleCollapsed} className={classNames('spread-btn')}>
            {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
          </Button>
        </div>
      </Resizable>
      <Resizable height={0} width={filterState.width} onResize={onFilterResize}>
        <div className="w-300px boxstyle relative" style={{ width: filterState.width + 'px' }}>
          <div className="flex justify-between p-15px">
            <div className="h-4% font-bold flex-none mr-1">数据筛选</div>
            <div className="flex">
              <Button size="small" onClick={ModalOpen}>
                导入筛选
              </Button>
              <Button size="small" onClick={Infofavoritesquery}>
                收藏筛选
              </Button>
              <Button size="small" onClick={cleanSearchvalue}>
                全部清空
              </Button>
            </div>
          </div>
          {loading && <HsAdminSpin />}
          {Collapseitems.length ? (
            <Collapse
              style={{ borderRadius: 0 }}
              items={Collapseitems.map((item: any) => ({
                key: item.id,
                label: item.name,
                children: filterOption(item, item.config.options)
              }))}
            />
          ) : (
            <Empty />
          )}
        </div>
      </Resizable>
      <Modal title="收藏筛选" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <div className="flex items-center">
          筛选名称：
          <HsAdminInput
            className="w-400px"
            value={favoritessearchValue}
            placeholder="请输入"
            onChange={(e: { target: { value: any } }) => setfavoritessearchValue(e.target.value)}
          />
        </div>
      </Modal>
      <Modal title="导入筛选" open={isqueryListModalOpen} footer={null} onCancel={() => setisqueryListModalOpen(false)}>
        <div className="flex items-center">
          请从收藏筛选中选择：
          <HsAdminInput
            className="w-200px"
            value={keywords}
            placeholder="请输入"
            onChange={(e: { target: { value: any } }) => setkeywords(e.target.value)}
            onPressEnter={getqueryList}
          />
          <Button className="ml-10px" size="small" type="primary" onClick={getqueryList}>
            搜索
          </Button>
        </div>
        <div className="mt-10px h-200px overflow-auto">
          {favoritesList.map((item: any, _index) => (
            <div key={item.id} className="flex">
              <div className="w-200px text-blue mr-20px cursor-pointer" onClick={() => handleCleanData(item)}>
                {item.name}
              </div>
              <Tooltip title={item.summary} trigger="hover">
                <div className="w-260px truncate">{item.summary}</div>
              </Tooltip>
            </div>
          ))}
        </div>
      </Modal>
    </div>
  )
}

export default Search
